function bwImg = getBw(Image)
%功能:由灰度图转为二值图
%   阈值分割,基于双峰灰度直方图寻找峰谷,其中包含平滑直方图的工作

hist1=imhist(Image);
hist2=hist1;
iter=0;
while 1
    [is,peak]=Bimodal(hist1);
    if is==0
        hist2(1)=(hist1(1)*2+hist1(2))/3;
        for j=2:255
            hist2(j)=(hist1(j-1)+hist1(j)+hist1(j+1))/3;
        end
        hist2(256)=(hist1(255)+hist1(256)*2)/3;
        hist1=hist2;
        iter=iter+1;
        if iter>1000
            break;
        end
    else
        break;
    end
end

[~,pos]=min(hist1(peak(1):peak(2)));
thresh=pos+peak(1);
if isempty(thresh)
    bwImg = imbinarize(Image);
    return
end

bwImg=zeros(size(Image));
bwImg(Image>thresh)=1;

% 如果输出的图像全黑或全白则该方法失效的处理
if all(bwImg == 1) | all(bwImg == 0)
    bwImg = imbinarize(Image);
    return
end
return

function [is,peak]=Bimodal(histgram)
    count = 0;
    peak(3) = 0;
    for i=2:255
        if histgram(i-1)<histgram(i) && histgram(i+1)<histgram(i)
            count=count+1;
            peak(count)=i;
            if count>2 
                is=0;
                return;
            end
        end
    end
    if count==2
        is=1;
    else
        is=0;
    end
end
end

